package team

import (
	"sanguo/cluster"
	"sanguo/codec/cs"
	"sanguo/node/common/orderMap"
	"sanguo/node/node_team/com"
	"time"

	"github.com/golang/protobuf/proto"
)

var encoder *cs.Encoder

type Team struct {
	TeamID        uint64
	TeamName      string
	TeamType      int32
	Header        uint64
	Roles         *orderMap.OrderMap
	Status        int32
	NextHeartbeat int64

	//发起挑战
	Fight *FightInviteInfo

	//申请入队限制
	AcceptApply int32
	ApplyRoles  map[uint64]*ApplyRole //申请的玩家

	RoomID int64
}

func (this *Team) GetRoles() []*Role {
	roles := []*Role{}
	for _, v := range this.Roles.OrderRead() {
		roles = append(roles, v.(*Role))
	}
	return roles
}

func (this *Team) GetRoleCount() int {
	return this.Roles.Len()
}

func (this *Team) GetFirstRole() *Role {
	return this.Roles.GetValueByIdx(0).(*Role)
}

func (this *Team) GetRole(roleID uint64) *Role {
	obj := this.Roles.GetValueByKey(roleID)
	if obj == nil {
		return nil
	} else {
		return obj.(*Role)
	}
}

func (this *Team) AddRole(r *Role) {
	this.Roles.Add(r.RoleID, r)
}

func (this *Team) DelRole(roleID uint64) {
	this.Roles.Del(roleID)
}

type ApplyRole struct {
	DestoryTime int64 //销毁时间
	UserID      string
	RoleID      uint64
	Game        cluster.PeerID
}

type Role struct {
	RoleID     uint64
	UserID     string
	Level      int32  //角色等级
	Name       string //角色名
	Portrait   int32  //头像
	Outline    int32  //外形
	Face       int32
	Hair       int32
	HairColor  int32
	EyeColor   int32
	Cloth      int32
	ClothColor int32
	Weapon1    int32
	Game       cluster.PeerID

	Status      int32
	OffLineTime int64 //玩家离线后启用

	//InviteTeam map[uint64]*Team //受邀请的队伍
}

func (this *Role) SendToClient(msg proto.Message) {
	com.SendToClient(this.Game, this.UserID, msg)
}

func (this *Role) SetOffLineTime() {
	this.Status = com.RoleStatus_Offline
	this.OffLineTime = time.Now().Unix()
}

func (this *Role) ClearOffLineTime() {
	this.Status = com.RoleStatus_Online
	this.OffLineTime = 0
}

func (this *Role) CheckOffLineKick(now time.Time) bool {
	if now.Unix() > this.OffLineTime+com.OffLineKickTime {
		return true
	}
	return false
}

type FightInviteInfo struct {
	//邀请信息
	BattleLevelType int32 //副本类型
	AgreeCount      int32
	DisAgreeCount   int32
	DestoryTime     int64 //销毁时间
	//玩家回复
	RoleReply map[uint64]int32 //0待操作 1同意 2拒绝
}

func (this *Team) NewFightInfo(battleLevelType int32) {
	_fight := &FightInviteInfo{
		BattleLevelType: battleLevelType,
		AgreeCount:      1,
		DisAgreeCount:   0,
		DestoryTime:     time.Now().Unix() + com.FightInviteTime + 5,
		RoleReply:       map[uint64]int32{},
	}
	for _, r := range this.GetRoles() {
		if r.RoleID == this.Header {
			_fight.RoleReply[r.RoleID] = 1
		} else {
			_fight.RoleReply[r.RoleID] = 0
		}

	}

	this.Fight = _fight
	UpdateFightInvite(this)
}
